package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"homework10/cache"
	"homework10/model"
	"strconv"
	"time"
)

func Add(c *gin.Context) {

	title := c.PostForm("title")
	content := c.PostForm("content")
	anchor := c.PostForm("anchor")

	if title == "" || content == "" || anchor == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}

	data := model.Article{
		Title:   title,
		Content: content,
		Anchor:  anchor,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	redis_key := "article_add_" + strconv.Itoa(int(data.ID))
	var article model.Article
	model.DB.Where("id=?", data.ID).First(&article).Debug()
	jsonData, _ := json.Marshal(&article)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func Del(c *gin.Context) {
	id := c.PostForm("id")

	var article model.Article

	err := model.DB.Where("id=?", id).Delete(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "article" + id
	cache.Rdb.Del(cache.Ctx, redis_key)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

func List(c *gin.Context) {
	var article []model.Article

	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if cacheData == "" {
		model.DB.Find(&article)
		jsonData, _ := json.Marshal(&article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	}

	model.DB.Find(&article)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取列表成功",
		"data": article,
	})
	return

}
